package com.zmc.member.application.impl;

import com.zmc.common.domain.es.EsSkuAttr;
import com.zmc.common.domain.es.EsSkuEntity;
import com.zmc.common.domain.query.coupon.CouponFeignQuery;
import com.zmc.common.domain.query.goods.GoodSkuFeignQuery;
import com.zmc.common.domain.resp.coupon.CouponAllFeignResp;
import com.zmc.common.domain.vo.coupon.CouponFeignVo;
import com.zmc.common.domain.vo.coupon.FullReductionFeignVo;
import com.zmc.common.domain.vo.coupon.LadderFeignVo;
import com.zmc.common.exception.base.BusinessException;
import com.zmc.common.utils.JsonUtils;
import com.zmc.common.utils.StringUtils;
import com.zmc.common.vo.GoodsVo;
import com.zmc.common.vo.SummaryVo;
import com.zmc.member.application.OrderPreApplicationService;
import com.zmc.member.infrastructure.bean.vo.PreOrderVo;
import com.zmc.member.infrastructure.bean.vo.ReceiveAddressVo;
import com.zmc.member.infrastructure.bean.vo.ShoppingCartVo;
import com.zmc.member.infrastructure.service.MemberReceiveAddressService;
import com.zmc.member.infrastructure.bean.response.PreOrderDetailResp;
import com.zmc.member.infrastructure.enums.PreOrderEnum;
import com.zmc.member.feign.CouponFeignService;
import com.zmc.member.feign.SearchFeignService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author：zmc
 * @Date：2024/11/6 15:33
 */

@Component
public class OrderPreApplicationServiceImpl implements OrderPreApplicationService {

    public static Logger log = LoggerFactory.getLogger(OrderPreApplicationServiceImpl.class);

    @Autowired
    private ShoppingCartCacheApplicationServiceImpl shoppingCartCacheApplicationService;

    @Autowired
    private MemberReceiveAddressService memberReceiveAddressService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Autowired
    private CouponFeignService couponFeignService;

    public static String upLoadPrefix = "http://localhost:8080/api";


    @Override
    public PreOrderDetailResp pre(PreOrderVo preOrderVo) {
        PreOrderDetailResp detail = new PreOrderDetailResp();
        //查询配送地址列表
        List<ReceiveAddressVo> addressList = memberReceiveAddressService.listReceiveAddress();
        detail.setUserAddresses(addressList);
        //查询被选中购物车列表
        GoodSkuFeignQuery query = new GoodSkuFeignQuery();
        List<String> skuIds = new ArrayList<>();
        List<ShoppingCartVo> shoppingCartVoList = new ArrayList<>();
        //立即购买(默认选中一个)
        if (PreOrderEnum.BUY_FIRST.getCode() == preOrderVo.getType()) {
            if (StringUtils.isEmpty(preOrderVo.getSkuId())) {
                throw new BusinessException("请选择商品再进行结算");
            }
            skuIds.add(preOrderVo.getSkuId());
            ShoppingCartVo vo = new ShoppingCartVo();
            vo.setSkuId(preOrderVo.getSkuId());
            vo.setCount(preOrderVo.getCount());
            shoppingCartVoList.add(vo);
        } else {
            //从购物车列表获取已选中sku
            shoppingCartVoList = shoppingCartCacheApplicationService.getSelectedList();
            List<String> selectedSkuIds = shoppingCartVoList.stream().map(ShoppingCartVo::getSkuId).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(selectedSkuIds)) {
                throw new BusinessException("请先从购物车选择商品");
            }
            skuIds.addAll(selectedSkuIds);
        }
        query.setSkuIds(skuIds);
        List<EsSkuEntity> esSkuList = JsonUtils.transToArrayClass(searchFeignService.getSkuInfosBySkuIds(query), EsSkuEntity.class);
        List<GoodsVo> list = new ArrayList<>();
        SummaryVo summary = new SummaryVo();
        //查询优惠活动
        CouponFeignQuery couponQuery = new CouponFeignQuery();
        couponQuery.setType(2);
        couponQuery.setSkuIds(esSkuList.stream().map(EsSkuEntity::getSkuId).collect(Collectors.toList()));
        List<CouponAllFeignResp> couponList = JsonUtils.transToArrayClass(couponFeignService.getCouponDetail(couponQuery), CouponAllFeignResp.class);
        for (EsSkuEntity esSku : esSkuList) {
            shoppingCartVoList.stream().filter(item -> Objects.equals(esSku.getSkuId(), item.getSkuId())).findFirst().ifPresent(shoppingCartVo -> {
                GoodsVo goodsVo = new GoodsVo();
                goodsVo.setSpuId(esSku.getSpuId());
                goodsVo.setSkuId(esSku.getSkuId());
                goodsVo.setName(esSku.getSpuTitle());
                goodsVo.setPicture(upLoadPrefix + esSku.getSkuImg());
                goodsVo.setCount(shoppingCartVo.getCount());
                goodsVo.setSkuId(esSku.getSkuId());
                goodsVo.setAttrsText(esSku.getAttrs().stream().map(EsSkuAttr::getPropertyValue).collect(Collectors.joining(" ")));
                goodsVo.setPrice(esSku.getSkuPrice());
                BigDecimal decimal = new BigDecimal(shoppingCartVo.getCount());
                goodsVo.setTotalPrice(esSku.getSkuPrice().multiply(decimal));
                goodsVo.setTotalPayPrice(esSku.getSkuPrice().multiply(decimal));
                summary.setGoodsCount(summary.getGoodsCount() + shoppingCartVo.getCount());
                summary.setTotalPrice(summary.getTotalPayPrice().add(goodsVo.getTotalPrice()));
                summary.setTotalPayPrice(summary.getTotalPayPrice().add(goodsVo.getTotalPayPrice()));
                couponList.stream().filter(item -> item.getSkuId().equals(esSku.getSkuId())).findFirst().ifPresent(item -> {
                    //sku总价
                    BigDecimal skuTotalPrice = goodsVo.getTotalPrice();
                    //sku数量
                    Long count = goodsVo.getCount();
                    //满减规则
                    FullReductionFeignVo reduction = item.getReduction();
                    BigDecimal reduceAmount = BigDecimal.ZERO;
                    if (reduction != null) {
                        goodsVo.setReduction(item.getReduction());
                        if (skuTotalPrice.compareTo(reduction.getFullPrice()) >= 0) {
                            reduceAmount = reduceAmount.add(reduction.getReducePrice());
                        }
                    }
                    //打折活动
                    LadderFeignVo ladder = item.getLadder();
                    if (ladder != null) {
                        goodsVo.setLadder(item.getLadder());
                        if (ladder.getFullCount() <= count) {
                            reduceAmount = reduceAmount.add(skuTotalPrice.subtract(skuTotalPrice.multiply(ladder.getDiscount())));
                        }
                    }
                    //优惠卷
                    CouponFeignVo coupon = item.getCoupon();
                    if (coupon != null) {
                        goodsVo.setCoupon(item.getCoupon());
                        if (coupon.getMinPoint().compareTo(skuTotalPrice) <= 0) {
                            reduceAmount = reduceAmount.add(coupon.getAmount());
                        }
                    }
                    //计算所有优惠活动后应付金额
                    summary.setTotalPayPrice(summary.getTotalPayPrice().subtract(reduceAmount));
                });
                //查询sku优惠卷活动
                list.add(goodsVo);
            });
        }
        detail.setGoods(list);
        detail.setSummary(summary);
        return detail;
    }

}
